package com.github.postsanf.yinian.timeline;
import android.app.Service;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.YNTimeLineActivity;
import com.github.postsanf.yinian.adapter.TimelineSpinerAdapter;
import com.github.postsanf.yinian.bean.YNTimeCompass;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCompassResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.view.GlobeViewSwitchView;
import com.github.postsanf.yinian.view.LoopMonthSwitchView;
import com.github.postsanf.yinian.view.OnAlbumSelcetListener;
import com.github.postsanf.yinian.view.OnCenterClickListener;
import com.github.postsanf.yinian.view.OnItemSelcetListener;
import com.github.postsanf.yinian.view.ResourceUtil;
import com.github.postsanf.yinian.view.TimeLinePickerView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class SecondFragment extends BaseTimelineFragment {
    private  List<String> data;
    private TimeLinePickerView date_pv;
    private GlobeViewSwitchView switchView;
    private HashMap<String,String> picUrlsKey = new HashMap<>();
    private ArrayList<String>       mGroupList = new ArrayList<>();
    private ArrayList<Integer>      mGroupIDList = new ArrayList<>();
    private TimelineSpinerAdapter   mAdapter;
    private PopupWindow             popupWindow;
    private LinearLayout            layout;
    private ListView                listView;
    private Context                 mContext;
    private List<YNTimeCompass>     timeCompassData = new ArrayList<>();
    private View                    mView;
    private TextView                tv_timeline_group_name;
    private LoopMonthSwitchView     curMonthView;
    private RelativeLayout rl_timeline_group_name;
    private int[] mAnimationViewIds = {
            R.id.timeline_second_center, R.id.timeline_second_gball,
            R.id.timeline_second_ship,R.id.rl_second_return
    };
    private int                     initpos;

    private Animation getBallAnimation(int resID){
        Animation animation = AnimationUtils.loadAnimation(getActivity(),resID);
        return animation;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        mView =inflater.inflate(R.layout.timeline_second, container, false);
        mContext = getActivity();
        initView();
        initData();
        return  mView;
    }
    private void initView(){
        switchView = (GlobeViewSwitchView)mView.findViewById(R.id.globeView);
        tv_timeline_group_name = (TextView) mView.findViewById(R.id.tv_timeline_group_name);
        rl_timeline_group_name = (RelativeLayout) mView.findViewById(R.id.rl_timeline_group_name);
        int width ;
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager manager = (WindowManager) getActivity().getSystemService(Service.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        for(int i=0;i< 3;i++){
            final LoopMonthSwitchView monthView = new LoopMonthSwitchView(getActivity());
            monthView.setmCenterClickListener(new OnCenterClickListener(){
                @Override
                public void onCenterClick(){
                    // 点击开启忆年时光记忆
                    ((YNTimeLineActivity)getActivity()).switchPage(2);
                }
            });
            monthView.setmItemSelcetListener(new OnItemSelcetListener() {
                @Override
                public void onSelect(int position) {
                    TextView textView = (TextView) monthView.getViewByPos(position).findViewById(ResourceUtil.getId( mContext == null? getActivity():mContext, "tv_loopView"));
                    // 当前月份
                    ((YNTimeLineActivity)getActivity()).setCurMonth(textView.getText().toString());
                    // 切换中间显示图片
                    monthView.showCenterView(getAddress());
                }
            });
            switchView.addView(monthView);
        }
        switchView.setR(width/2);
        switchView.setAuto(false);
        switchView.setScrollInterval(5000);
        switchView.setLeftScroll(false);
        switchView.setmAlbumSelcetListener(new OnAlbumSelcetListener(){
            @Override
            public void onSelect(int position, View view) {
                if (timeCompassData.size() > 0) {
                    ((YNTimeLineActivity)getActivity()).setCurGroup(String.valueOf(timeCompassData.get(getAlbumPosByPos(position)).getGroupid()));
                    // 设置组名
                    tv_timeline_group_name.setText(timeCompassData.get(getAlbumPosByPos(position)).getGname());
                    ((LoopMonthSwitchView)view).showCenterView(getAddress());
                    curMonthView = (LoopMonthSwitchView) view;
                    // 设置当前组的年份月份
                    setYearAndMonth(timeCompassData.get(getAlbumPosByPos(position)).getGroupid());
                }
            }
        });
        // 返回忆年首页
        mView.findViewById(mAnimationViewIds[3]).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        date_pv = (TimeLinePickerView) mView.findViewById(R.id.date_pv);
    }

    private void setYearAndMonth(int curGroup){
        for(int i=0;i<timeCompassData.size();i++){
            if(timeCompassData.get(i).getGroupid() == curGroup && timeCompassData.get(i).getDate().size()>0){
//                showLog(timeCompassData.get(i).getDate().get(0).getYear()+"============================"+timeCompassData.get(i).getDate().get(0).getMonth());
                setCurMonth(Integer.parseInt(timeCompassData.get(i).getDate().get(0).getMonth()));
                setCurYear(timeCompassData.get(i).getDate().get(0).getYear());
            }
        }
    }

    // 设置当前年份
    private void setCurYear(String year){
        for (int i=0;i<data.size();i++){
            if (data.get(i).equals(year)){
                initpos = i;
                date_pv.setSelected(i);
                date_pv.performSelect();
                date_pv.invalidate();
            }
        }
    }

    // 设置当前月份
    private void setCurMonth(int month){
        if (curMonthView!=null){
            curMonthView.turn2month(month);
        }else{
            int pos = switchView.getSelectPosition()>= 0 ? switchView.getSelectPosition() : 3 + switchView.getSelectPosition();
            ((LoopMonthSwitchView)switchView.getChildAt(pos)).turn2month(month);
        }
    }

    private String getAddress(){
        String res = picUrlsKey.get(((YNTimeLineActivity)getActivity()).getCurGroup()+"_"+((YNTimeLineActivity)getActivity()).getCurYear()+"_"+((YNTimeLineActivity)getActivity()).getCurMonth());
        return res==null? "" : res;
    }

    private int getAlbumPosByPos(int position){
        int size = timeCompassData.size();
        int res = -1;
        if(size > 0){
            res = position>=0 ? Math.abs(position) % size : Math.abs(size + position) % size;
        }
        return res;
    }

    private void setDate(){
        int minDate = Calendar.getInstance().get(Calendar.YEAR);
        int maxDate = minDate;
        for(int i=0;i<timeCompassData.size();i++){
            for (int j=0;j<timeCompassData.get(i).getDate().size();j++){
                if(Integer.parseInt(timeCompassData.get(i).getDate().get(j).getYear()) < minDate){
                    minDate = Integer.parseInt(timeCompassData.get(i).getDate().get(j).getYear());
                }else if(Integer.parseInt(timeCompassData.get(i).getDate().get(j).getYear()) > maxDate){
                    maxDate = Integer.parseInt(timeCompassData.get(i).getDate().get(j).getYear());
                }
            }
        }
        ((YNTimeLineActivity)getActivity()).setCurYear(String.valueOf(minDate));
        data = new ArrayList<String>();
        for (int k = minDate; k <=maxDate; k++){
            data.add(String.valueOf(k));
        }
        if(data.size()>0){
            date_pv.setData(data);
            date_pv.setOnSelectListener(new TimeLinePickerView.onSelectListener(){
                @Override
                public void onSelect(String text){
                    ((YNTimeLineActivity)getActivity()).setCurYear(text);
                    if (curMonthView!=null){
                        curMonthView.showCenterView(getAddress());
                    }else{
                        int pos = switchView.getSelectPosition()>= 0 ? switchView.getSelectPosition() : 3 + switchView.getSelectPosition();
                        ((LoopMonthSwitchView)switchView.getChildAt(pos)).showCenterView(getAddress());
                    }
                }
            });
            date_pv.setSelected(initpos);
        }
        mAdapter = new TimelineSpinerAdapter(getActivity(), mGroupList);
        if(mGroupList.size()>0){
            tv_timeline_group_name.setText(mGroupList.get(0));
        }
        // 下拉框
        rl_timeline_group_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                showWindow(rl_timeline_group_name, tv_timeline_group_name);
            }
        });
    }

    private void initData(){
        LinkedHashMap<String,String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID,String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL)+getString(R.string.ynShowTimeCompass))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true){
                    @Override
                    public void onSuccess(String s, Response<String> response){
                        YNCompassResponse resCompass = gson.fromJson(s, YNCompassResponse.class);
                        if (resCompass!=null && ReqUtils.isSuccess(resCompass.getCode()) && resCompass.getData().size()>0){
                            picUrlsKey.clear();
                            timeCompassData.addAll(resCompass.getData());
                            ((YNTimeLineActivity)getActivity()).setCurGroup(String.valueOf(timeCompassData.get(0).getGroupid()));
                            for (int i=0;i<timeCompassData.size();i++){
                                for(int j=0;j<timeCompassData.get(i).getDate().size();j++){
                                    picUrlsKey.put(timeCompassData.get(i).getGroupid()+"_"+timeCompassData.get(i).getDate().get(j).getYear()+"_"+String.valueOf(Integer.parseInt(timeCompassData.get(i).getDate().get(j).getMonth())),timeCompassData.get(i).getDate().get(j).getPicAddress());
                                }
                                mGroupList.add(timeCompassData.get(i).getGname());
                                mGroupIDList.add(timeCompassData.get(i).getGroupid());
                            }
                            setDate();
                        }else{
                            showToast("请求失败");
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, Response<String> response){
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
        super.onViewCreated(view, savedInstanceState);
        mView.findViewById(mAnimationViewIds[0]).startAnimation(getBallAnimation(R.anim.anim_second_center));
        mView.findViewById(mAnimationViewIds[1]).startAnimation(getBallAnimation(R.anim.anim_second_gball));
    }

    @Override
    public int[] getChildViewIds() {
        return new int[]{
                R.id.timeline_second_center,R.id.timeline_second_gball,
                R.id.timeline_second_ship,R.id.rl_second_return
        };
    }

    @Override
    public int getRootViewId() {
        return R.id.root_timeline_second;
    }

    // 相册组列表框
    public void showWindow(View position, final TextView txt){
        layout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.yn_spiner_window_layout, null);
        listView = (ListView) layout.findViewById(R.id.lv_spiner_item);
        listView.setAdapter(mAdapter);
        popupWindow = new PopupWindow(position);
        // 设置弹框的宽度为布局文件的宽
        popupWindow.setWidth(rl_timeline_group_name.getWidth());
        popupWindow.setHeight(rl_timeline_group_name.getHeight()*4);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(layout);
        int[] location = new int[2];
        rl_timeline_group_name.getLocationOnScreen(location);
        popupWindow.showAtLocation(rl_timeline_group_name, Gravity.NO_GRAVITY, location[0], location[1]-popupWindow.getHeight());
        // listView的item点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                txt.setText(mGroupList.get(arg2));
                // 设置当前相册
                for(int i=0;i<mGroupList.size();i++){
                    if(mGroupIDList.get(i) == timeCompassData.get(i).getGroupid()){
                        ((YNTimeLineActivity)getActivity()).setCurGroup(String.valueOf(timeCompassData.get(i).getGroupid()));
                        switchView.setCurDegree(i);
                        setYearAndMonth(timeCompassData.get(i).getGroupid());
                    }
                }
                try{
                    if (curMonthView!=null){
                        curMonthView.showCenterView(getAddress());
                    }else{
                        int pos = switchView.getSelectPosition()>= 0 ? switchView.getSelectPosition() : 3 + switchView.getSelectPosition();
                        ((LoopMonthSwitchView)switchView.getChildAt(pos)).showCenterView(getAddress());
                    }
                }catch (NullPointerException e){}
                popupWindow.dismiss();
                popupWindow = null;
            }
        });
    }
}